/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FrmSetor.java
 *
 * Created on Nov 13, 2009, 11:30:52 PM
 */

package br.com.digitalpoint.form;

import br.com.digitalpoint.Funcionario;
import br.com.digitalpoint.Setor;
import br.com.digitalpoint.dao.FuncionarioDAO;
import br.com.digitalpoint.dao.SetorDAO;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JOptionPane;

/**
 *
 * @author rodrigo
 */
public class FrmSetor extends javax.swing.JFrame {

    private ArrayList<Funcionario> listaFuncionario;

    public void habilitarBotao(JButton j)
    {
        j.setEnabled(true);
    }

    public void desabilitarBotao(JButton j)
    {
        j.setEnabled(false);
    }


    public void carregaComboFuncionarios()
    {
       try
       {
          listaFuncionario = new FuncionarioDAO().consultarTodosFuncionarios();
          cbxSupervisor.removeAllItems();
          cbxSupervisor.addItem("0-Escolha");
          cbxSupervisor.setSelectedItem("0-Escolha");
          for (int i = 0; i <listaFuncionario.size(); i ++)
          {
              //obtem um objeto Disciplina da lista’
              Funcionario d = listaFuncionario.get(i);
              //obtem o codigo
              int cod_supervisor = d.getMatricula();
              //obtem o nome
              String nome = cod_supervisor+"-"+d.getNome();
              //adiciona o nome no combobox
              cbxSupervisor.addItem(nome);             
          }
          cbxSupervisor.setEnabled(true);
        } 
       catch (Exception e)
       {
            JOptionPane.showMessageDialog(null, "ERRO: "+e.getMessage());
       }
    }

    public void carregaComboFuncionariosSel(int codSup)
    {
       try
       {
          listaFuncionario = new FuncionarioDAO().consultarTodosFuncionarios();
          cbxSupervisor.removeAllItems();
          for (int i = 0; i <listaFuncionario.size(); i ++)
          {
              //obtem um objeto Disciplina da lista’
              Funcionario d = listaFuncionario.get(i);
              //obtem o codigo
              int cod_supervisor = d.getMatricula();
              //obtem o nome
              String nome = cod_supervisor+"-"+d.getNome();
              //adiciona o nome no combobox
              cbxSupervisor.addItem(nome);
              if(cod_supervisor==codSup)
              {
                 cbxSupervisor.setSelectedItem(nome);
              }
          }
          cbxSupervisor.setEnabled(true);
        }
       catch (Exception e)
       {
            JOptionPane.showMessageDialog(null, "ERRO: "+e.getMessage());
       }
    }

    
    /** Creates new form FrmSetor */
    public FrmSetor() {
        initComponents();
        carregaComboFuncionarios();
        desabilitarBotao(btnAlterar);
        desabilitarBotao(btnExcluir);
        habilitarBotao(btnInserir);
    }

    private void limparCampos()
    {
        txtCodigo.setText(null);
        txtNome.setText(null);
        txtDescricao.setText(null);
        txtNomeConsulta.setText(null);
        cbxSupervisor.setSelectedIndex(0);
        desabilitarBotao(btnAlterar);
        desabilitarBotao(btnExcluir);
        habilitarBotao(btnInserir);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlSetor = new javax.swing.JPanel();
        lblCodigo = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        lblNome = new javax.swing.JLabel();
        txtNome = new javax.swing.JTextField();
        lblDescricao = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtDescricao = new javax.swing.JTextArea();
        btnLimpar = new javax.swing.JButton();
        btnInserir = new javax.swing.JButton();
        lblSupervisor = new javax.swing.JLabel();
        cbxSupervisor = new javax.swing.JComboBox();
        btnAlterar = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        btnListar = new javax.swing.JButton();
        lblTitulo = new javax.swing.JLabel();
        pnlConsulta = new javax.swing.JPanel();
        lblNomeConsulta = new javax.swing.JLabel();
        txtNomeConsulta = new javax.swing.JTextField();
        btnConsultar = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("DIGITALPOINT - SETORES");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setResizable(false);

        pnlSetor.setBorder(javax.swing.BorderFactory.createTitledBorder("Informações"));
        pnlSetor.setToolTipText("");

        lblCodigo.setText("Código:");

        txtCodigo.setEditable(false);

        lblNome.setText("Nome:");

        lblDescricao.setText("Descrição:");

        txtDescricao.setColumns(20);
        txtDescricao.setRows(5);
        jScrollPane1.setViewportView(txtDescricao);

        btnLimpar.setText("Limpar");
        btnLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimparActionPerformed(evt);
            }
        });

        btnInserir.setText("Inserir");
        btnInserir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnInserirActionPerformed(evt);
            }
        });

        lblSupervisor.setText("Supervisor:");

        cbxSupervisor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbxSupervisorActionPerformed(evt);
            }
        });

        btnAlterar.setText("Alterar");
        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });

        btnExcluir.setText("Excluir");
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        btnListar.setText("Listar");
        btnListar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnListarActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout pnlSetorLayout = new org.jdesktop.layout.GroupLayout(pnlSetor);
        pnlSetor.setLayout(pnlSetorLayout);
        pnlSetorLayout.setHorizontalGroup(
            pnlSetorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(pnlSetorLayout.createSequentialGroup()
                .addContainerGap()
                .add(pnlSetorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(pnlSetorLayout.createSequentialGroup()
                        .add(lblCodigo)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(txtCodigo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 50, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(pnlSetorLayout.createSequentialGroup()
                        .add(lblNome)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(txtNome, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 169, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 332, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(lblDescricao)
                    .add(pnlSetorLayout.createSequentialGroup()
                        .add(lblSupervisor)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(cbxSupervisor, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 263, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(pnlSetorLayout.createSequentialGroup()
                        .add(btnLimpar)
                        .add(18, 18, 18)
                        .add(btnInserir)
                        .add(14, 14, 14)
                        .add(btnAlterar)
                        .add(18, 18, 18)
                        .add(btnExcluir)
                        .add(18, 18, 18)
                        .add(btnListar)))
                .addContainerGap(89, Short.MAX_VALUE))
        );
        pnlSetorLayout.setVerticalGroup(
            pnlSetorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(pnlSetorLayout.createSequentialGroup()
                .addContainerGap()
                .add(pnlSetorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblCodigo)
                    .add(txtCodigo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(pnlSetorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblNome)
                    .add(txtNome, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(lblDescricao)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 98, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(pnlSetorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblSupervisor)
                    .add(cbxSupervisor, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(34, 34, 34)
                .add(pnlSetorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnLimpar)
                    .add(btnAlterar)
                    .add(btnInserir)
                    .add(btnExcluir)
                    .add(btnListar))
                .addContainerGap(29, Short.MAX_VALUE))
        );

        lblTitulo.setText("DIGITAL POINT - SETORES");

        pnlConsulta.setBorder(javax.swing.BorderFactory.createTitledBorder("Consulta"));

        lblNomeConsulta.setText("Nome do Setor:");

        btnConsultar.setText("Consultar");
        btnConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsultarActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout pnlConsultaLayout = new org.jdesktop.layout.GroupLayout(pnlConsulta);
        pnlConsulta.setLayout(pnlConsultaLayout);
        pnlConsultaLayout.setHorizontalGroup(
            pnlConsultaLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(pnlConsultaLayout.createSequentialGroup()
                .addContainerGap()
                .add(lblNomeConsulta)
                .add(18, 18, 18)
                .add(txtNomeConsulta, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 233, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(39, 39, 39)
                .add(btnConsultar)
                .addContainerGap(22, Short.MAX_VALUE))
        );
        pnlConsultaLayout.setVerticalGroup(
            pnlConsultaLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(pnlConsultaLayout.createSequentialGroup()
                .addContainerGap()
                .add(pnlConsultaLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblNomeConsulta)
                    .add(txtNomeConsulta, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(btnConsultar))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(20, 20, 20)
                        .add(lblTitulo))
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, pnlSetor, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jSeparator1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 502, Short.MAX_VALUE)))
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(pnlConsulta, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .add(18, 18, 18))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(lblTitulo)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(pnlConsulta, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(23, 23, 23)
                .add(pnlSetor, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(23, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimparActionPerformed
            limparCampos();
    }//GEN-LAST:event_btnLimparActionPerformed

    private void btnInserirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInserirActionPerformed

        //obtendo os valores do form e associando a variaveis
        String nome = txtNome.getText();
        String descricao = txtDescricao.getText();
        String cod_supervisor = (String)cbxSupervisor.getSelectedItem();
        String sub_cod_supervisor = cod_supervisor.substring(0,1);
        int sub_cod_supervisor1 = Integer.parseInt(sub_cod_supervisor);

        //setando objeto para enviar para o DAO
        Setor setor = new Setor();
        setor.setCod_supervisor(sub_cod_supervisor1);
        setor.setNome(nome);
        setor.setDescricao(descricao);

        //verificando preenchimento dos campos obrigatorios
        if(sub_cod_supervisor1!=0 && !(nome.equals("")))
        {
            //inserindo no banco
            SetorDAO setorDAO = new SetorDAO();
            try
            {
                setorDAO.incluir(setor);
                JOptionPane.showMessageDialog(null, "Setor incluido com sucesso.");
                limparCampos();
            }
            catch (Exception ex)
            {
                JOptionPane.showMessageDialog(null, "Não foi possivel incluir o Setor.\n" + "ERRO: "+ex.getMessage(), "ERRO", 0 );
            }
        }
        else
        {
            //mensagem para falta de campos obrigatórios
            JOptionPane.showMessageDialog(null, "Você precisa preencher os campos obrigatórios!");
        }
        
    }//GEN-LAST:event_btnInserirActionPerformed

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        // TODO add your handling code here:
        //obtendo os valores do form e associando a variaveis
        String nome = txtNome.getText();
        String descricao = txtDescricao.getText();
        String cod_supervisor = (String)cbxSupervisor.getSelectedItem();
        String sub_cod_supervisor = cod_supervisor.substring(0,1);
        int sub_cod_supervisor1 = Integer.parseInt(sub_cod_supervisor);
        int cod_setor = Integer.parseInt(txtCodigo.getText());

        //setando objeto para enviar para o DAO
        Setor setor = new Setor();
        setor.setCod_setor(cod_setor);
        setor.setCod_supervisor(sub_cod_supervisor1);
        setor.setNome(nome);
        setor.setDescricao(descricao);

        //verificando preenchimento dos campos obrigatorios
        if(sub_cod_supervisor1!=0 && !(nome.equals("")))
        {
            //inserindo no banco
            SetorDAO setorDAO = new SetorDAO();
            try
            {
                setorDAO.alterar(setor);
                JOptionPane.showMessageDialog(null, "Setor alterado com sucesso.");
                limparCampos();
            }
            catch (Exception ex)
            {
                JOptionPane.showMessageDialog(null, "Não foi possivel alterar o Setor.\n" + "ERRO: "+ex.getMessage(), "ERRO", 0 );
            }
        }
        else
        {
            //mensagem para falta de campos obrigatórios
            JOptionPane.showMessageDialog(null, "Você precisa preencher os campos obrigatórios!");
        }
    }//GEN-LAST:event_btnAlterarActionPerformed

    private void btnConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarActionPerformed
        try
        {
            Setor setor = new Setor();
            SetorDAO setorDAO = new SetorDAO();
            setor=setorDAO.consultar(txtNomeConsulta.getText());

            txtCodigo.setText(Integer.toString(setor.getCod_setor()));
            txtNome.setText(setor.getNome());
            txtDescricao.setText(setor.getDescricao());

            carregaComboFuncionariosSel(setor.getCod_supervisor());

            
            
            habilitarBotao(btnAlterar);
            habilitarBotao(btnExcluir);
            desabilitarBotao(btnInserir);
        }
        catch (Exception ex)
        {
            JOptionPane.showMessageDialog(null, "Setor nao encontrado!\n", "MESSAGEM", 2);
            limparCampos();
        }
    }//GEN-LAST:event_btnConsultarActionPerformed

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
        // TODO add your handling code here:
        try
        {
            int opcao = JOptionPane.showConfirmDialog(null, "Tem Certeza que deseja excluir esse Setor?", "Confirmação de Exclusão", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if(opcao == JOptionPane.YES_NO_OPTION)
            {
                SetorDAO setorDAO = new SetorDAO();
                setorDAO.excluir(Integer.parseInt(txtCodigo.getText()));
                JOptionPane.showMessageDialog(null, "Setor excluído com sucesso!", "RESULTADO", 1);
                limparCampos();
                desabilitarBotao(btnAlterar);
                desabilitarBotao(btnExcluir);
            }
            else
            {
                JOptionPane.showMessageDialog(null, "A exclusão foi cancelada!", "RESULTADO", 1);                
            }
        }
        catch (Exception ex)
        {
            JOptionPane.showMessageDialog(null, "Não foi possivel excluir Setor!\n" + "ERRO: " + ex.getMessage(), "ERRO", 0);
        }
    }//GEN-LAST:event_btnExcluirActionPerformed

    private void btnListarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnListarActionPerformed
        // TODO add your handling code here:
        pnlSetor.setVisible(false);
        
    }//GEN-LAST:event_btnListarActionPerformed

    private void cbxSupervisorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbxSupervisorActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cbxSupervisorActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrmSetor().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAlterar;
    private javax.swing.JButton btnConsultar;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnInserir;
    private javax.swing.JButton btnLimpar;
    private javax.swing.JButton btnListar;
    private javax.swing.JComboBox cbxSupervisor;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lblCodigo;
    private javax.swing.JLabel lblDescricao;
    private javax.swing.JLabel lblNome;
    private javax.swing.JLabel lblNomeConsulta;
    private javax.swing.JLabel lblSupervisor;
    private javax.swing.JLabel lblTitulo;
    private javax.swing.JPanel pnlConsulta;
    private javax.swing.JPanel pnlSetor;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JTextArea txtDescricao;
    private javax.swing.JTextField txtNome;
    private javax.swing.JTextField txtNomeConsulta;
    // End of variables declaration//GEN-END:variables

}
